package com.liyunc.demo.service;

import com.liyunc.demo.exception.DataMatchException;
import com.liyunc.demo.mapper.UserInfoMapper;
import com.liyunc.demo.pojo.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Slf4j
@Service
public class UserInfoService implements UserDetailsService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    //数据加密，在启动类中已经注入进IOC容器中
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 用户登录验证.
     */
    public List<UserInfo> findAll() {
        List<UserInfo> list = userInfoMapper.findAll();
        if (!list.isEmpty()) {
            return list;
        } else {
            log.info("server exception,find all fail");
            throw new DataMatchException("403", "find fail");
        }
    }

    /**
     * 用户注册.
     */
    public UserInfo register(UserInfo userInfo) {
        userInfo.setPassword(bCryptPasswordEncoder.encode(userInfo.getPassword()));

        int result = userInfoMapper.save(userInfo);
        if (result == 1) {
            log.info("user:[{}],register success", userInfo.getUsername());
            return userInfo;
        } else {
            log.info("server exception,register fail");
            throw new DataMatchException("403", "register fail");
        }
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = userInfoMapper.getUserByUsername(username);
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        if (userInfo != null) {
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_user"));
            return new User(
                userInfo.getUsername(),
                userInfo.getPassword(),
                grantedAuthorities);
        } else {
            throw new UsernameNotFoundException(username + "do not exist!");
        }
    }
}
